﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;
using WebNext.UI.Utils;
using System.Text;
using WebNext.UI.Models;
using WebNext.Domain.Entities;
using System.Threading;
using System.Configuration;
using WebNext.UI.Properties;
using System.Resources;
using System.Globalization;
using WebNext.UI.Utils.Mailing;

namespace WebNext.UI.Controllers
{
	public abstract class BaseController : Controller
	{
		private bool? isLogged;
		
		protected bool IsLogged
		{
			get 
			{
				if (this.isLogged == null)
				{
					this.isLogged = this.Request.IsAuthenticated;
				}
				return this.isLogged.Value; 
			}
		}
		
		protected ILog Log
		{
			get;
			set;
		}
		
		protected CultureId CultureId
		{
			get;
			set;
		}

		protected BaseController()
		{
			this.Log = LogManager.GetLogger(typeof(EntriesController));
			this.CultureId = (CultureId)Thread.CurrentThread.CurrentUICulture.LCID;
		}

		[HttpPost]
		public RedirectResult SetCulture(CultureId culture)
		{
			string cultureId = Convert.ToInt32(culture).ToString();
			if (this.Response.Cookies[Constants.Culture] != null)
			{
				this.Response.Cookies[Constants.Culture].Value = cultureId;
			}
			else
			{
				HttpCookie cookie = new HttpCookie(Constants.Culture, cultureId);
				cookie.Expires = DateTime.MaxValue;
				this.Response.Cookies.Add(cookie);
			}

			ResourceManager resourceManager = new ResourceManager(typeof(Resources));
			this.TempData[Constants.Message] = resourceManager.GetString("LanguageHasBeenChanged", new CultureInfo((int)culture));

			string path = string.Empty;
			if (this.Request.UrlReferrer.AbsolutePath == "/")
			{
				path = this.Request.UrlReferrer.AbsoluteUri;
			}
			else
			{
				path = this.Request.UrlReferrer.AbsoluteUri.Replace(this.Request.UrlReferrer.AbsolutePath, string.Empty);
			}
			return this.Redirect(path);
		}

		protected override void OnException(ExceptionContext filterContext)
		{
			Log.Error("Unexpected error", filterContext.Exception);
			this.SendEmailNotification(filterContext);

			base.OnException(filterContext);
		}

		private void SendEmailNotification(ExceptionContext filterContext)
		{
			bool exceptionNotificationEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailNotifyException"]);
			if (!exceptionNotificationEnabled)
			{
				return;
			}

			string subject = "Unhandled exception occured on web site!";

			StringBuilder bodyBuilder = new StringBuilder();
			bodyBuilder.AppendLine("TIME");
			bodyBuilder.AppendLine(DateTime.Now.ToString());
			bodyBuilder.AppendLine();

			bodyBuilder.AppendLine("ROUTE DATA");
			foreach (KeyValuePair<string, object> value in filterContext.RouteData.Values)
			{
				bodyBuilder.AppendFormat("{0} : {1}{2}", value.Key, value.Value, Environment.NewLine);
			}
			bodyBuilder.AppendLine();

			bodyBuilder.AppendLine("EXCEPTION");
			bodyBuilder.AppendLine(filterContext.Exception.ToString());

			IEmailNotifier emailNotifier = new GmailNotifier();
			emailNotifier.Notify(subject, bodyBuilder.ToString());
		}
	}
}